no-cache & no-store

JavaScript Cache Prevention Techniques (2025-04-14 17:50:34)

Question:js script 可以添加字段禁止缓存吗
Answer:

JavaScript 防止缓存的方法

是的,在 JavaScript 中可以添加字段或参数来禁止缓存。主要有以下几种方法:

1. 通过添加时间戳或随机参数

1
2
3
4
5
// 添加时间戳防止缓存
const url = 'example.com/api/data?nocache=' + new Date().getTime();

// 或使用随机数
const url = 'example.com/api/data?nocache=' + Math.random();

2. 使用 Fetch API 时设置缓存控制

1
2
3
4
5
6
7
8
9
fetch('example.com/api/data', {
headers: {
'Cache-Control': 'no-cache, no-store, must-revalidate',
'Pragma': 'no-cache',
'Expires': '0'
}
})
.then(response => response.json())
.then(data => console.log(data));

3. 使用 XMLHttpRequest 设置缓存控制

1
2
3
4
5
6
7
8
9
10
11
const xhr = new XMLHttpRequest();
xhr.open('GET', 'example.com/api/data');
xhr.setRequestHeader('Cache-Control', 'no-cache, no-store, must-revalidate');
xhr.setRequestHeader('Pragma', 'no-cache');
xhr.setRequestHeader('Expires', '0');
xhr.onload = function() {
if (xhr.status === 200) {
console.log(JSON.parse(xhr.responseText));
}
};
xhr.send();

4. 在引用静态资源时防止缓存

1
2
3
4
5
6
7
8
// 为脚本添加版本号或时间戳
const script = document.createElement('script');
script.src = 'script.js?v=' + new Date().getTime();
document.head.appendChild(script);

// 为图片添加时间戳
const img = new Image();
img.src = 'image.jpg?t=' + new Date().getTime();
这些方法通过不同的方式告诉浏览器不要使用缓存版本的资源,而是每次都重新请求最新的资源。
Question:cache-control 中的 no-cache 和 no-store 的区别
Answer:

Cache-Control 中 no-cache 和 no-store 的区别

no-cache 和 no-store 的主要区别

no-cache

  • **不意味着"不缓存"**,而是"必须重新验证"
  • 允许客户端存储资源的副本
  • 每次使用缓存前,必须向服务器发送请求进行验证(使用 ETag 或 Last-Modified)
  • 如果服务器确认内容未变化,则可以使用缓存版本(返回 304 Not Modified)
  • 适用于经常变化但有时保持不变的内容
1
2
3
4
5
fetch('example.com/api/data', {
headers: {
'Cache-Control': 'no-cache'
}
});

no-store

  • 完全禁止缓存
  • 不允许任何方式的存储
  • 每次访问都必须从服务器重新获取完整内容
  • 客户端不能保存资源的副本
  • 适用于敏感信息或始终需要最新数据的场景
1
2
3
4
5
fetch('example.com/api/data', {
headers: {
'Cache-Control': 'no-store'
}
});

实际使用场景

no-cache 适用于:

  • 新闻网站文章
  • 产品页面
  • 需要最新但允许验证后使用缓存的资源

no-store 适用于:

  • 银行交易信息
  • 个人隐私数据
  • 一次性令牌
  • 实时数据(如股票价格)

组合使用

在实践中,为了最大程度防止缓存,通常会组合使用多个指令:
1
2
3
4
5
6
7
fetch('example.com/api/data', {
headers: {
'Cache-Control': 'no-cache, no-store, must-revalidate',
'Pragma': 'no-cache', // 兼容 HTTP/1.0
'Expires': '0' // 兼容旧浏览器
}
});
总结:no-cache 允许缓存但需要验证,no-store 则完全禁止缓存。